package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNameRolePermission = "role_permissions"

// RolePermission mapped from table <role_permissions>
type RolePermission struct {
	RoleID       int64 `gorm:"column:role_id;type:bigint;primaryKey" json:"roleId"`
	PermissionID int64 `gorm:"column:permission_id;type:bigint;primaryKey" json:"permissionId"`
}

// TableName RolePermission's table name
func (*RolePermission) TableName() string {
	return TableNameRolePermission
}

// CreateRolePermission creates a new RolePermission in the database.
func (m *RolePermission) CreateRolePermission() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetRolePermissionByID retrieves a RolePermission by its ID from the database.
func (m *RolePermission) GetRolePermissionByID(id int64) (*RolePermission, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // RolePermission not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateRolePermission updates an existing RolePermission in the database.
func (m *RolePermission) UpdateRolePermission() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteRolePermission deletes a RolePermission by its ID from the database.
func (m *RolePermission) DeleteRolePermission(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}

// 通过角色id获取权限
func GetRolePermissionByRoleID(roleId int64) ([]*RolePermission, error) {
	var rolePermissions []*RolePermission
	if err := global.Db.Where("role_id = ?", roleId).Find(&rolePermissions).Error; err != nil {
		return nil, err
	}
	return rolePermissions, nil
}
